package com.sunfeng.a05;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2022/4/8  22:28
 */
public class ComponentScanPostProcessor implements BeanFactoryPostProcessor {

    /**
     * context.refresh 会调用这个方法
     *
     * @param configurableListableBeanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

        try {
            // 1、获取包扫描的路径
            ComponentScan componentScan = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

            // 5.4、获取 生成Bean Name 自动生成器
            AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();

            if (!ObjectUtils.isEmpty(componentScan)) {
                //2、获取所有的包名, 进行遍历=
                for (String basePackage : componentScan.basePackages()) {
                    //3、扫描包下面的所有class文件
                    //3.1、处理包名为路径名
                    String path = "classpath*:" + basePackage.replace(".", "/") + "/**/*.class";
                    CachingMetadataReaderFactory readerFactory = new CachingMetadataReaderFactory();
                    // 3.2、获取路径下所有的资源
                    Resource[] resources = new PathMatchingResourcePatternResolver().getResources(path);
                    for (Resource resource : resources) {
                        //4、读取资源的元数据metadataReader
                        MetadataReader reader = readerFactory.getMetadataReader(resource);
                        AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata();
                        ClassMetadata classMetadata = reader.getClassMetadata();
                        //5、检查类上是否添加了@Component注解 或者@Component派生
                        if (annotationMetadata.hasAnnotation(Component.class.getName())
                                || annotationMetadata.hasMetaAnnotation(Component.class.getName())) {
                            //5.1、 获取BeanDefinition
                            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                                    .genericBeanDefinition(classMetadata.getClassName())
                                    .getBeanDefinition();
                            /**
                             * 5.2、判断bean工厂类型是否符合强转类型，进行类型转换
                             */
                            if (configurableListableBeanFactory instanceof DefaultListableBeanFactory) {
                                DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) configurableListableBeanFactory;
                                /**
                                 * 5.3、 获取bean的名称 并完成注册
                                 */
                                String name = generator.generateBeanName(beanDefinition, beanFactory);
                                /**
                                 * 5.5、完成注册
                                 */
                                beanFactory.registerBeanDefinition(name, beanDefinition);
                            }
                        }
                    }

                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
